package com.delivery.deliverysystem.shiro;

import com.delivery.deliverysystem.pojo.DO.SysAuthority;
import com.delivery.deliverysystem.pojo.DO.User;
import com.delivery.deliverysystem.service.UserService;
import com.delivery.deliverysystem.service.impl.SysAuthorityServiceImpl;
import com.delivery.deliverysystem.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 验证用户合法性
 * 定义shiro框架：用户域
 */

@Slf4j
public class UserRealm extends AuthorizingRealm {
    //Shiro框架的两个核心模块：认证和授权
    
    @Autowired
    private UserService userService;

    @Autowired
    private SysAuthorityServiceImpl sysAuthorityService;


    @Override
    public boolean supports(AuthenticationToken token) {

        //return token instanceof JWTToken ;
        if (token instanceof JWTToken) {
            String jwtToken = (String) token.getCredentials();
            String username = JWTUtil.getUsername(jwtToken);
            return username != null;
        }
        return false;
    }


    /**
     * 权限认证登录
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        String token = (String) authenticationToken.getCredentials();
        //解密，获取userId
        String username = JWTUtil.getUsername(token);
        System.out.println(username);
        System.out.println(username +"afdsarerasd--------------------------------------------------------");
        log.info("{}账号验证", username);//普通用户
        User currentUser = userService.findByUserCode(username);
        try {
            //通过认证后返回
            if (currentUser != null && JWTUtil.verify(token)){
                return new SimpleAuthenticationInfo(token,token,this.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


//        if (username.startsWith("D") && username.length() == 12){
//            //普通用户
//            SysUsers currentUser = sysUserService.findSysUserByUsername(username);
//            try {
//                //通过认证后返回
//                if (currentUser != null && JWTUtil.verify(token)){
//                    return new SimpleAuthenticationInfo(token,token,this.getName());
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }else {
//            SysAdmin currentUser = sysAdminService.findSysAdminByUsername(username);
//            try {
//                //通过认证后返回
//                if (currentUser != null && JWTUtil.verify(token)){
//                    System.out.println("22222222222222");
//                    return new SimpleAuthenticationInfo(token,token,this.getName());
//                    //return new SimpleAuthenticationInfo(currentUser, token, this.getName());
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        System.out.println("111111111111111111111111111111");
        return null;
    }

    /**
     * 授权处理：保存用户角色
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = principalCollection.toString();
//        System.out.println("->>>>>>>" + token);
        String authorityId = JWTUtil.getUserAuthorityId(token);;
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> role = new HashSet<>();
        //记录当前登录用户的角色：0普通用户、1管理员
        // role.add(user.getUserAuthority()+"");
        SysAuthority sysAuthority = sysAuthorityService.findSysAuthority(Integer.parseInt(authorityId));
        role.add(sysAuthority.getAuthorityRole());
        authorizationInfo.setRoles(role);
        return authorizationInfo;
    }



}

